package com.beta.platform.rest.interceptor;

import com.alibaba.fastjson.JSON;
import com.beta.platform.rest.auth.Signet;
import com.beta.platform.rest.auth.SignetSecurity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * 解析Signet
 */
public class AddSignetInterceptor extends HandlerInterceptorAdapter {

	private static final String SIGNET = "signet";


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取请求头Signet，解析出资源的分享者
		String signetJson = request.getHeader(SIGNET);
		if (StringUtils.isNotBlank(signetJson)) {
			signetJson = new String(Base64.getDecoder().decode(signetJson), StandardCharsets.UTF_8);
			Signet signet = JSON.parseObject(signetJson, Signet.class);
			//兼容 上下游返回的userId格式为corpId/userId
			String userId =  signet.getUserId();
			if(null != signet && userId.contains("/")){
				signet.setCorpId(userId.split("/")[0]);
				signet.setUserId(userId.split("/")[1]);
			}
			SignetSecurity.setSignet(signet);
		}
		return super.preHandle(request, response, handler);
	}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		SignetSecurity.clean();
    }

}
